package com.cc.springboot_test.aop;

import com.cc.springboot_test.converter.ObjectConverter;
import org.apache.commons.lang3.RandomStringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

/**
 * Controller层日志记录切面
 * 1、输出请求返回报文
 * 2、输出接口耗时
 */
@Aspect
@Component
public class RestControllerLoggingAspect {

    private static final Logger logger = LoggerFactory.getLogger(RestControllerLoggingAspect.class);

    // 记录请求 url , queryString , requestBody , 耗时 等
    @Around("com.cc.springboot_test.aop.CommonPointCutConfig.restControllers()")
    public Object loggingRequestResponse(ProceedingJoinPoint joinPoint) throws Throwable {
        // 日志未启用直接继续
        if (!logger.isInfoEnabled()) {
            return joinPoint.proceed();
        }

        long start = System.currentTimeMillis();

        // 人工设置traceId
        String randomStr = RandomStringUtils.random(16, false, true);
        MDC.put("traceId", randomStr);

        // 记录请求报文
        logger.info("request body: {}", joinPoint.getArgs());

        boolean success = false;
        try {
            Object result = joinPoint.proceed();
            // 记录返回报文
            logger.info("response body: {}", result);
            return result;
        } finally {
            // 记录请求耗时
            logger.info("{} | {} | {}", joinPoint.getSignature(), joinPoint.toShortString(), success, System.currentTimeMillis() - start);
        }
    }
}
